<?php

namespace app\controllers\merchant\uni\log;

use app\controllers\admin\base\AdminController;

use app\redis\api\Error as Model;

/**
 * Class LogsController
 * @package app\controllers\admin
 */
class ErrorController extends AdminController
{
    public function actionList()
    {
        $export = $this->post('export');
        $url = $this->post('url');
        $id = $this->post('id');

        $page = intval($this->post('page', 1));
        $page_size = intval($this->post('pageSize', 10));

        $sort = $this->post('sort');

        $query = Model::find();

        if ($sort) {
            $prop = substr($sort, 0, 1);
            $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
            $order = substr($sort, 1);
            $query->orderBy([$order => $prop]);
        } else {
            $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC]);
        }

        if ($id) {
            $query->andWhere(['id' => $id]);
        }
        if ($url) {
            // redis 不支持like
            $query->andWhere(['url' => $url]);
        }

        if ($export) {
            return $this->success($query->asArray()->all());
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->asArray()
            ->all();

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);
    }

    public function actionDelete()
    {
        $id = $this->post('id');
        $model = Model::findOne(['id' => $id]);
        if ($model->delete()) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionBatchDelete()
    {
        $ids = $this->post('ids');
        Model::deleteAll(['id' => $ids]);

        return $this->success();
    }

    public function actionClear()
    {
        Model::deleteAll();

        return $this->success();
    }

}